package com.david.aop;

import com.david.dao.LogMapper;
import com.david.entity.OperateLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author David
 * 这个切面用于记录接口处、dao处的访问及操作记录
 * Aspect 用于标注这是一个切面类
 */
@Aspect
@Component
@Slf4j
public class LogAop {

    @Resource
    LogMapper logMapper;

    @Resource
    HttpServletRequest request;

    /**
     * 这个切入点的表达式的意思是所有Controller中的所有方法进行拦截
     */
    @Pointcut("execution(* com.david.controller.*.*(..))")
    public void logController(){}

    @Pointcut("execution(* com.david.dao.ConsoleMapper.*(..))")
    public void logDao(){};

    /**
     * 接口调用之后就记录日志
     * @param joinPoint 调用的哪个接口及其相关信息
     */
    @AfterReturning("logController()")
    public void logControllerImpl(JoinPoint joinPoint){
        String info = joinPoint.getSignature().toString();
        log.info("请求的参数为：" + Arrays.toString(joinPoint.getArgs()) + "        " +
                 "返回值的类型为：" + info.substring(0, info.indexOf(' ')) + "        " +
                 "调用的接口为：" + info.substring(info.indexOf(' ')));
        OperateLog operateLog = new OperateLog();
//        operateLog.setOperateName(request.getRemoteAddr());
        operateLog.setOperateName(request.getHeader("X-Real-IP"));
        if(operateLog.getOperateName() == null){
            operateLog.setOperateName(request.getRemoteAddr());
        }
        operateLog.setOperateUrl(request.getRequestURL().toString());
        operateLog.setOperateParam(Arrays.toString(joinPoint.getArgs()));
        operateLog.setOperateInterface(info.substring(info.indexOf(' ')));
        operateLog.setMethod(request.getMethod());
        logMapper.saveOperateLog(operateLog);
    }

    /**
     * Dao层调用之后就记录日志
     * @param joinPoint 调用的哪个Dao层及其相关信息
     */
    @After("logDao()")
    public void logDaoImpl(JoinPoint joinPoint){
        String info = joinPoint.getSignature().toString();
        log.info("请求的参数为：" + Arrays.toString(joinPoint.getArgs()) + "        " +
                "返回值的类型为：" + info.substring(0, info.indexOf(' ')) + "        " +
                "调用的接口为：" + info.substring(info.indexOf(' ')));

        OperateLog operateLog = new OperateLog();
//        operateLog.setOperateName(request.getRemoteAddr());
        operateLog.setOperateName(request.getHeader("X-Real-IP"));
        if(operateLog.getOperateName() == null){
            operateLog.setOperateName(request.getRemoteAddr());
        }
        operateLog.setOperateUrl(request.getRequestURL().toString());
        operateLog.setOperateParam(Arrays.toString(joinPoint.getArgs()));
        operateLog.setOperateInterface(info.substring(info.indexOf(' ')));
        operateLog.setMethod(request.getMethod());
        logMapper.saveOperateLog(operateLog);

    }
}
